/**
 *  文件转base64 (TODO:base64太长卡死)
 * @param {File} file 文件
 */
export const fileToBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e: any) => {
      resolve(e.target.result)
    }

    /* const imgUrl = URL.createObjectURL(file)
    resolve(imgUrl) */
  })
}

/**
 * base64 转 Blob （若存在，需手动去除 data:image/jpeg;base64,）
 * @param {string} base64
 */
export const dataURLtoBlob = (base64: any) => {
  const arrs = base64.split(';base64,')
  const mime = arrs.length === 2 ? arrs[0].replace('data:', '') : 'image/jpeg'
  const b64 = arrs.length === 2 ? arrs[1] : base64 // base64.replace('data:image/jpeg;base64,', '')
  const byteCharacters = window.atob(b64)
  const byteNumbers = new Array(byteCharacters.length)
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  const byteArray = new Uint8Array(byteNumbers)
  const blob = new Blob([byteArray], { type: mime })
  return blob
}

/**
 * 设置图片水印
 * @param {object} 水印参数 {url：图片base64 或者 url地址，content:'水印内容',cb:回调方法}
 */
export const setWaterMark = ({
  url = '',
  textAlign = 'center',
  textBaseline = 'Middle',
  font = '20px Microsoft Yahei',
  fillStyle = 'rgba(0, 0, 0, .9)',
  content = '',
  cb = null
}: any = {}) => {
  const img = new Image()
  img.src = url
  img.crossOrigin = 'anonymous'
  img.onload = function () {
    const canvas = document.createElement('canvas')
    const _ix = img.width
    const _iy = img.height
    canvas.width = _ix
    canvas.height = _iy
    const ctx: any = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0)
    ctx.textAlign = textAlign
    ctx.textBaseline = textBaseline
    ctx.font = font
    ctx.fillStyle = fillStyle
    // ctx.translate(0, 0)
    // ctx.rotate((Math.PI / 180) * 15) //旋转
    //水印密度
    /* for (let i = 0; i < _iy / 120; i++) {
      for (let j = 0; j < _ix / 50; j++) {
        console.log(i * 120, j * 100)
        ctx.fillText(content, i * 120, j * 50, _ix)
      }
    } */
    if (content instanceof Array) {
      const startY = _iy - 10
      const lastI = content.length - 1
      for (let i = 0; i <= lastI; i++) {
        const y = startY - (lastI - i) * 30
        ctx.fillText(content[i], _ix - 120, y, _ix)
      }
    } else if (typeof content === 'string') {
      ctx.fillText(content, _ix - 120, _iy - 10, _ix)
    }
    const base64Url = canvas.toDataURL()
    cb && cb(base64Url)
  }
}
/**
 * 图片压缩
 * @param {string} base64   base64编码
 * @param {string} w 图片宽度
 * @param {string} imageType 图片类型
 * @param {Function} callback  回调方法
 * */
export const cutImageBase64 = (base64: any, w: any, imageType: any = 'jpeg', callback: any) => {
  const newImage = new Image()
  let quality = 0.6 // 压缩系数0-1之间
  newImage.src = base64
  newImage.setAttribute('crossOrigin', 'Anonymous') // url为外域时需要
  let imgWidth: any = '',
    imgHeight: any = ''
  newImage.onload = function () {
    imgWidth = newImage.width
    imgHeight = newImage.height
    const canvas = document.createElement('canvas')
    const ctx: any = canvas.getContext('2d')
    if (Math.max(imgWidth, imgHeight) > w) {
      if (imgWidth > imgHeight) {
        canvas.width = w
        canvas.height = (w * imgHeight) / imgWidth
      } else {
        canvas.height = w
        canvas.width = (w * imgWidth) / imgHeight
      }
    } else {
      canvas.width = imgWidth
      canvas.height = imgHeight
      // quality = 0.8
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
    const mime = `image/${imageType}`
    let base64 = canvas.toDataURL('', quality) // 压缩语句
    // 如想确保图片压缩到自己想要的尺寸,如要求在50-1024kb之间，请加以下语句，quality初始值根据情况自定
    while (base64.length / 1024 > 1024) {
      quality -= 0.01
      base64 = canvas.toDataURL(mime, quality)
    }
    // 防止最后一次压缩低于最低尺寸，只要quality递减合理，无需考虑
    while (base64.length / 1024 < 50) {
      quality += 0.001
      base64 = canvas.toDataURL(mime, quality)
    }
    callback && callback(base64) // 必须通过回调函数返回，否则无法及时拿到该值
  }
}

/**
 * 图片处理
 * @param {string} imgUrl  图片文件地址或者图片base64编码
 * @param {string,Array} watermarkContent  水印内容
 */
export const imageProcessing = (type = 'jpeg', imgUrl: string, watermarkContent: any, callback: any) => {
  setWaterMark({
    url: imgUrl,
    content: watermarkContent,
    cb: (base64Url: any) => {
      cutImageBase64(base64Url, 6144, type, (base64: any) => {
        const blob = dataURLtoBlob(base64)
        // console.log('blob', blob)
        callback && callback(blob)
      })
    }
  })
}
